package com.vercon.moensmart.dialog

import android.net.Uri
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.vercon.common.presenter.common.MirrorResultView
import com.vercon.moensmart.R
import com.vercon.moensmart.databinding.DialogTowelRackControllerLayoutBinding
import com.vercon.moensmart.dialog.base.BaseDialogFragment
import com.vercon.moensmart.mode.request.DeviceCommandRequest
import com.vercon.moensmart.mode.response.BaseResponse
import com.vercon.moensmart.presenter.MoenPresenter
import com.vercon.moensmart.utils.FrescoUtil
import com.vercon.moensmart.viewmodel.DeviceControllerViewModel
import com.vercon.moensmart.viewmodel.SystemViewModel

class TowelRackControllerDialog : BaseDialogFragment<DialogTowelRackControllerLayoutBinding>() {

    val moenPresenter = MoenPresenter()
    var deviceId : String? = null
    var productId : String? = null
    var deviceControllerViewModel : DeviceControllerViewModel? = null
    val mGson = Gson()
    companion object{
        val DEMO_DEVICE_ID = "weikuangvercon"
        val DEVICE_ID = "DEVICE_ID"
        val PRODUCT_ID = "PRODUCT_ID"
        val PRODUCT_PIC = "PRODUCT_PIC"
        val PRODUCT_NAME = "PRODUCT_NAME"
    }
    override fun onStart() {
        super.onStart()
        val dm = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        dialog!!.window!!.setLayout(resources.getDimension(com.vercon.common.R.dimen.dp_950).toInt(), resources.getDimension(com.vercon.common.R.dimen.dp_885).toInt())
    }

    override fun onCreateViewBinding(inflater: LayoutInflater, parent: ViewGroup?): DialogTowelRackControllerLayoutBinding {
        return DialogTowelRackControllerLayoutBinding.inflate(inflater,parent,false)
    }

    override fun initView(view: View?) {
        deviceControllerViewModel = ViewModelProvider(requireActivity())[DeviceControllerViewModel::class.java]

        deviceId = arguments?.getString(ToiletControllerDialog.DEVICE_ID,"")
        productId = arguments?.getString(ToiletControllerDialog.PRODUCT_ID,"")

        getDeviceInfo()

        FrescoUtil.loadImage(binding?.pictureImageview, Uri.parse("res://" + context?.packageName + "/" + R.mipmap.ic_towel_rack_big))
        binding?.tvSmallTitle?.text = "产品型号 " + arguments?.getString(ToiletControllerDialog.PRODUCT_NAME,"")
    }

    override fun initListener(view: View?) {


        deviceControllerViewModel?.getTowelRackLiveData()?.observe(this){
            if(it != null){
                for ((i,bean) in it.withIndex()){
                    if(bean.device_id.equals(deviceId)){
                        //开关
                        binding?.igSwitch?.isSelected = (bean.power_switch == 1)
                        binding?.tvSwitchState?.text = if(binding?.igSwitch?.isSelected!!) "ON" else "OFF"

                        //定时
                        binding?.tvTimer1?.isSelected = (bean.time == 2)
                        binding?.tvTimer2?.isSelected = (bean.time == 4)
                        binding?.tvTimer3?.isSelected = (bean.time == 8)
                        binding?.tvTimer4?.isSelected = (bean.time == 0)

                        //温度
                        binding?.seekbar?.isEnabled = binding?.igSwitch?.isSelected!!
                        binding?.seekbar?.progress = bean.temperature
                    }
                }

            }
        }


        binding?.tvTimer1?.setOnClickListener {
            theAllTimeSwitch(binding?.tvTimer1?.isSelected!!,2)
        }
        binding?.tvTimer2?.setOnClickListener {
            theAllTimeSwitch(binding?.tvTimer2?.isSelected!!,4)
        }
        binding?.tvTimer3?.setOnClickListener {
            theAllTimeSwitch(binding?.tvTimer3?.isSelected!!,8)
        }
        binding?.tvTimer4?.setOnClickListener {
            theAllTimeSwitch(binding?.tvTimer4?.isSelected!!,0)
        }

        //开关
        binding?.igSwitch?.setOnClickListener {
            val switchState = if(binding?.igSwitch?.isSelected!!) 0 else 1
            deviceControllerViewModel?.setTowelRack_PowerSwitch(deviceId,switchState)

            if(switchState == 0){
                theAllTimeSwitch(true,-1)
            }

            val command = HashMap<String,Any>()
            command["power"] = switchState
            //command["temperature_set"] = getRealTemperature(binding?.seekbar?.progress!!)
            sendCommand(command)
        }

        //温度
        binding?.seekbar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if(fromUser){
                    deviceControllerViewModel?.setTowelRack_Temperature(deviceId,progress)
                    if(binding?.igSwitch?.isSelected!!){
                        val command = HashMap<String,Any>()
                        command["temperature_set"] = getRealTemperature(progress)
                        sendCommand(command)
                    }
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })


        binding?.igClose?.setOnClickListener { dismiss() }
    }


    fun theAllTimeSwitch(isSelect : Boolean,time : Int){

        if(binding?.igSwitch?.isSelected!!){
            deviceControllerViewModel?.setTowelRack_Time(deviceId,if(isSelect) -1 else time)

            if(!isSelect){
                val command = HashMap<String,Any>()
                command["time_set"] = time
                sendCommand(command)
                deviceControllerViewModel?.setTowelRack_Time(deviceId,time)
            }
        }

    }

    private fun sendCommand(command : HashMap<String,Any>){
        if(deviceId.isNullOrEmpty() || productId.isNullOrEmpty()){
            return
        }
        if(deviceId.equals(DEMO_DEVICE_ID)){
            return
        }
        val request = DeviceCommandRequest(deviceId,productId, DeviceCommandRequest.Command(command))
        moenPresenter.sendDeviceCommand(request, object : MirrorResultView<BaseResponse<Any>> {
            override fun onSuccess(result: BaseResponse<Any>?) {
                getDeviceInfo()
            }
            override fun onError(code: Int, message: String?) {

            }
        })
    }

    private fun getDeviceInfo(){
        if(deviceId.isNullOrEmpty() || productId.isNullOrEmpty()){
            return
        }
        if(deviceId.equals(DEMO_DEVICE_ID)){
            return
        }
//        moenPresenter.getDeviceInfo(deviceId,productId,object  : MirrorResultView<BaseResponse<Any>>{
//            override fun onSuccess(result: BaseResponse<Any>?) {
//                val data : JsonObject? = mGson.toJsonTree(result?.data).asJsonObject
//
//                val time : Int? = data?.get("time_set")?.asInt
//                time?.let { deviceControllerViewModel?.setTowelRack_Time(deviceId,it) }
//
//                val temperature : Int? = data?.get("temperature_set")?.asInt
//                temperature?.let {
//                    when(it){
//                        45->{
//                            deviceControllerViewModel?.setTowelRack_Temperature(deviceId,0)
//                        }
//                        55->{
//                            deviceControllerViewModel?.setTowelRack_Temperature(deviceId,1)
//                        }
//                        65->{
//                            deviceControllerViewModel?.setTowelRack_Temperature(deviceId,2)
//                        }
//                        else -> {}
//                    }
//                }
//
//                val power : Int? = data?.get("power")?.asInt
//                power?.let { deviceControllerViewModel?.setTowelRack_PowerSwitch(deviceId,it) }
//
//            }
//            override fun onError(code: Int, message: String?) {
//
//            }
//        })
    }


    fun getRealTemperature(v : Int) : Int{
        return when(v){
            0->{ 45 }
            1->{ 55 }
            2->{ 65 }
            else->{ 45 }
        }
    }

    override val isFullScreen: Boolean
        get() = false

}